'use strict';

angular.module('app')
  .factory('companyService', [
    '$http',
    '$state',
    '$q', /*解决回调地狱问题*/
    function($http, $state, $q) {
      return {
        query: function() {
          var defer = $q.defer(); //声明延后执行
          $http({
            method: 'GET',
            url: '/data/company.json?id=' + $state.params.id //获取json数据
          }).then(function(data, status, headers, config) {
            defer.resolve(data.data); //执行成功
          }).then(function(data, status, headers, config) {
            defer.reject(); //执行失败
          });
          return defer.promise; //返回获取的数据
        }
      }
    }
  ])
  .controller('companyCtrl', [
    '$scope',
    '$http',
    'companyService',
    function($scope, $http, companyService) {
      var promise = companyService.query(); //同步调用，获取promise的接口
      promise.then(function(success) {
          $scope.company = success; //调用接口，如果获取数据成功 resolve()方法的实参
          $scope.$broadcast('bcComId', { id: $scope.company.id });
        },
        function(error) {
          $scope.company = {
            error: 'data was not found...' //如果获取数据失败，调用reject()方法
          };
        });
      $scope.$on('bcId', function(event, data) {
        console.log(event, data);
      });

    }
  ])
